<!-- src/views/Home.vue -->
<template>
  <div class="home">
    <h1 class="page-title">数据统计</h1>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <StatCard
          :label="'总产品数'"
          :value="stats?.totalProducts || 0"
          :icon="Box"
          icon-bg="#409EFF"
          :clickable="true"
          @click="() => $router.push('/products')"
          :quick-actions="[
            { key: 'view', label: '查看产品', icon: Goods },
            { key: 'add', label: '添加产品', icon: Plus }
          ]"
          @action="handleStatAction"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          :label="'总库存价值'"
          :value="stats?.totalValue || 0"
          :icon="Money"
          icon-bg="#67C23A"
          :formatter="(val) => '¥' + val.toLocaleString()"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          :label="'总订单数'"
          :value="orderStats.totalOrders"
          :icon="ShoppingCart"
          icon-bg="#E6A23C"
          :clickable="true"
          @click="() => $router.push('/orders')"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          :label="'已完成订单收入'"
          :value="orderStats.totalRevenue"
          :icon="TrendCharts"
          icon-bg="#F56C6C"
          :formatter="(val) => '¥' + val.toLocaleString()"
          :clickable="true"
          @click="showRevenueDetails"
          :quick-actions="[
            { key: 'export', label: '导出报表', icon: Download },
            { key: 'detail', label: '查看详情', icon: View }
          ]"
          @action="handleStatAction"
        />
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="6">
        <StatCard
          :label="'注册用户'"
          :value="dashboardData.totalUsers || 0"
          :icon="User"
          icon-bg="#909399"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          :label="'待处理订单'"
          :value="orderStats.pendingOrders"
          :icon="Clock"
          icon-bg="#FF9800"
          :clickable="true"
          @click="() => $router.push('/orders?status=pending')"
          :quick-actions="[
            { key: 'batch-process', label: '批量处理', icon: Operation }
          ]"
          @action="handleBatchProcess"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          :label="'产品分类'"
          :value="stats?.totalCategories || 0"
          :icon="Collection"
          icon-bg="#9C27B0"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          :label="'已完成订单'"
          :value="orderStats.completedOrders"
          :icon="CircleCheck"
          icon-bg="#00BCD4"
          :clickable="true"
          @click="() => $router.push('/orders?status=completed')"
        />
      </el-col>
    </el-row>

    <!-- 时间范围选择器 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>图表数据时间范围</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
          <el-button type="primary" @click="refreshCharts">刷新数据</el-button>
        </div>
      </template>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单趋势</span>
              <el-radio-group v-model="trendChartType" size="small" @change="refreshCharts">
                <el-radio-button label="count">订单数</el-radio-button>
                <el-radio-button label="revenue">收入</el-radio-button>
                <el-radio-button label="both">两者</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <OrderTrendChart
            :data="chartData.orderTrend || []"
            :show-revenue="trendChartType === 'revenue'"
            :show-both="trendChartType === 'both'"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单状态统计</span>
            </div>
          </template>
          <StatusStatsChart :data="chartData.statusStats || {}" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>销售分类分布</span>
              <el-radio-group v-model="distributionChartType" size="small" @change="refreshCharts">
                <el-radio-button label="pie">饼图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <SalesDistributionChart
            :data="chartData.salesDistribution || []"
            :chart-type="distributionChartType"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>实时统计（最近24小时）</span>
              <el-tag type="success">实时更新</el-tag>
            </div>
          </template>
          <div class="realtime-stats">
            <div class="realtime-item">
              <span class="label">订单数：</span>
              <span class="value">{{ realtimeStats.ordersCount || 0 }}</span>
            </div>
            <div class="realtime-item">
              <span class="label">收入：</span>
              <span class="value">¥{{ (realtimeStats.revenue || 0).toLocaleString() }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表和列表 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 订单状态分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
              <el-button type="primary" text @click="$router.push('/orders')">查看全部</el-button>
            </div>
          </template>
          <div class="status-list">
            <div class="status-item">
              <el-tag type="warning">待处理</el-tag>
              <span class="status-count">{{ orderStats.pendingOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <el-tag type="info">处理中</el-tag>
              <span class="status-count">{{ orderStats.processingOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <el-tag type="">已发货</el-tag>
              <span class="status-count">{{ orderStats.shippedOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <el-tag type="success">已完成</el-tag>
              <span class="status-count">{{ orderStats.completedOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <el-tag type="danger">已取消</el-tag>
              <span class="status-count">{{ orderStats.cancelledOrders || 0 }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 产品分类分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>产品分类分布</span>
              <el-button type="primary" text @click="$router.push('/products')">管理产品</el-button>
            </div>
          </template>
          <div class="category-list">
            <div 
              v-for="(count, category) in categoryStats" 
              :key="category" 
              class="category-item"
            >
              <span class="category-name">{{ getCategoryName(category) }}</span>
              <el-progress 
                :percentage="(count / stats.totalProducts * 100).toFixed(0)" 
                :stroke-width="10"
                :format="() => count"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近订单 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>最近订单</span>
          <el-button type="primary" text @click="$router.push('/orders')">查看全部订单</el-button>
        </div>
      </template>
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="id" label="订单ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column label="商品" width="200">
          <template #default="{ row }">
            <div v-for="item in row.items" :key="item.productId">
              {{ item.name }} x {{ item.quantity }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="总价" width="100">
          <template #default="{ row }">¥{{ row.totalPrice }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="下单时间" width="180" />
      </el-table>
      <el-empty v-if="recentOrders.length === 0" description="暂无订单数据" />
    </el-card>

    <!-- 热门产品 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>热门产品</span>
          <el-button type="primary" text @click="$router.push('/products')">管理产品</el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in hotProducts" :key="product.id">
          <el-card class="product-card" shadow="hover">
            <div class="product-info">
              <h4>{{ product.name }}</h4>
              <p class="description">{{ product.description || '' }}</p>
              <p class="price">¥{{ product.price }}</p>
              <p class="category">分类: {{ getCategoryName(product.category) }}</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" v-if="hotProducts.length === 0">
          <el-empty description="暂无热门产品" :image-size="80" />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useProductStore } from '../stores/product'
import { useOrderStore } from '../stores/order'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import StatCard from '@/components/StatCard.vue'
import OrderTrendChart from '@/components/Charts/OrderTrendChart.vue'
import SalesDistributionChart from '@/components/Charts/SalesDistributionChart.vue'
import StatusStatsChart from '@/components/Charts/StatusStatsChart.vue'
import { 
  Box, Money, Collection, Warning, ShoppingCart, TrendCharts, 
  User, Clock, CircleCheck, Goods, Plus, Download, View, Operation
} from '@element-plus/icons-vue'

const router = useRouter()
const productStore = useProductStore()
const orderStore = useOrderStore()
const { stats } = storeToRefs(productStore)
const hotProducts = ref([])
const dashboardData = ref({
  totalUsers: 0
})

// 图表数据
const chartData = ref({
  orderTrend: [],
  salesDistribution: [],
  statusStats: {},
  realtimeStats: {}
})

const realtimeStats = ref({
  ordersCount: 0,
  revenue: 0,
  hourlyData: {}
})

// 时间范围
const dateRange = ref([])

// 图表类型
const trendChartType = ref('count')
const distributionChartType = ref('pie')

// 定时器
let refreshTimer = null

const categoryMap = {
  makeup: '美妆',
  clothing: '服饰',
  digital: '数码',
  appliance: '电器',
  fresh: '生鲜',
  outdoor: '户外'
}

const getCategoryName = (category) => {
  return categoryMap[category] || category
}

const orderStats = computed(() => {
  return orderStore.getOrderStats()
})

const categoryStats = computed(() => {
  if (!stats.value || !stats.value.categoryStats) return {}
  return stats.value.categoryStats
})

const recentOrders = computed(() => {
  return [...orderStore.orders]
    .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    .slice(0, 5)
})

const getStatusText = (status) => {
  const map = {
    pending: '待处理',
    processing: '处理中',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    processing: 'info',
    shipped: '',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

const fetchDashboardData = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('/api/admin/dashboard', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    if (response.data && response.data.success) {
      dashboardData.value = response.data.data
      // 如果服务器返回了订单统计，也可以更新到 orderStore
      if (response.data.data.orderStats) {
        console.log('从服务器获取到订单统计:', response.data.data.orderStats)
      }
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const token = localStorage.getItem('token')
    const params = {}
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    const response = await axios.get('/api/admin/dashboard/charts', {
      headers: {
        Authorization: `Bearer ${token}`
      },
      params
    })
    
    if (response.data && response.data.success) {
      chartData.value = response.data.data
      realtimeStats.value = response.data.data.realtimeStats || {}
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  refreshCharts()
}

// 刷新图表
const refreshCharts = () => {
  fetchChartData()
}

// 处理统计卡片操作
const handleStatAction = async (action, value) => {
  switch (action) {
    case 'view':
      router.push('/products')
      break
    case 'add':
      router.push('/products')
      ElMessage.info('请在产品管理页面添加新产品')
      break
    case 'export':
      ElMessage.info('导出功能开发中')
      break
    case 'detail':
      showRevenueDetails()
      break
  }
}

// 显示收入详情
const showRevenueDetails = () => {
  ElMessageBox.alert(
    `已完成订单总收入：¥${orderStats.value.totalRevenue.toLocaleString()}`,
    '收入详情',
    {
      confirmButtonText: '确定'
    }
  )
}

// 批量处理订单
const handleBatchProcess = async () => {
  try {
    // 获取待处理订单
    const pendingOrders = orderStore.orders.filter(o => o.status === 'pending')
    
    if (pendingOrders.length === 0) {
      ElMessage.warning('没有待处理的订单')
      return
    }
    
    const { value: status } = await ElMessageBox.prompt(
      `共有 ${pendingOrders.length} 个待处理订单，请选择要更新到的状态：`,
      '批量处理订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'select',
        inputOptions: {
          processing: '处理中',
          shipped: '已发货',
          completed: '已完成',
          cancelled: '已取消'
        }
      }
    )
    
    if (!status) return
    
    const token = localStorage.getItem('token')
    const orderIds = pendingOrders.map(o => o.id)
    
    const response = await axios.post('/api/admin/orders/batch-update', {
      orderIds,
      status
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.success) {
      ElMessage.success(response.data.message)
      // 刷新订单列表和图表
      await orderStore.fetchOrders()
      refreshCharts()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量处理订单失败:', error)
      ElMessage.error(error.response?.data?.message || '批量处理失败')
    }
  }
}

onMounted(async () => {
  // 并行加载所有数据，提高加载速度
  await Promise.all([
    productStore.fetchStats(),
    orderStore.fetchOrders(),
    fetchDashboardData(),
    fetchChartData()
  ])
  
  // 获取热门产品
  const response = await productStore.fetchHotProducts()
  if (response.success) {
    hotProducts.value = response.data
  }
  
  // 设置默认时间范围（最近30天）
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]
  
  // 每30秒刷新图表数据（实时更新）
  refreshTimer = setInterval(() => {
    fetchChartData()
  }, 30000)
  
  // 调试：输出订单统计信息
  console.log('订单统计:', orderStore.getOrderStats())
  console.log('订单数据:', orderStore.orders)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
})
</script>

<style scoped>
.home {
  padding: 0;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 24px;
  color: white;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.product-card {
  margin-bottom: 20px;
}

.description {
  color: #909399;
  font-size: 12px;
  margin: 5px 0;
}

.product-info h4 {
  margin: 10px 0 5px 0;
  font-size: 14px;
}

.price {
  color: #E6A23C;
  font-weight: bold;
  margin: 5px 0;
}

.category {
  color: #909399;
  font-size: 12px;
  margin: 5px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-list {
  padding: 10px 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-count {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.category-list {
  padding: 10px 0;
}

.category-item {
  margin-bottom: 15px;
}

.category-item:last-child {
  margin-bottom: 0;
}

.category-name {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
}

.realtime-stats {
  padding: 20px;
}

.realtime-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.realtime-item:last-child {
  border-bottom: none;
}

.realtime-item .label {
  font-size: 16px;
  color: #606266;
}

.realtime-item .value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
</style>